import React, { Component } from 'react'
import ctx from '@/assets/js/ctx'
import styles from './index.module.scss'
import classnames from 'classnames'
import { Toast ,Modal} from 'antd-mobile';
import { Player,BigPlayButton } from 'video-react';

const alert = Modal.alert;

export class VideoPage extends Component {

    static contextType = ctx

    constructor(){
        super()

        this.state ={
            videoDetail:{},

            time:'',

            opacity:0,

            checkedPos:'intro',
            barWidth:0,

            isFixed:false,
            isIntro:true,

            isFollowed:false,
            isxiala:true,
            liked:false,

            similarList:[],

            isFavorite:false,
            token:'',
            commentList:[],

            text:'',
            isPlay: "block"

        }
    }

    get durationFrom(){
        let time = this.state.time
            time = time.split(':')
            time = time.map(e =>{
                if(e*1 < 10){
                    e='0'+e;
                }
                return e
            })
            if(time.length<3){
                time.unshift("00")
            }
            return time.join(':')
    }

    reqVideoDetail(aid){
        return this.context.axios.post('/bulubulu/api/video/detail',{
            aid
        })
        .then((res) => {
            const {code,msg,info} = res
            if(code == 1){
                this.setState({
                    videoDetail: info[0],
                    time:info[0].duration
                })
            }else{
                console.log(msg)
            }
        })        
    }

    checkedTab = (tab) => {

        const checkedPos = this[tab].getBoundingClientRect().left
        const barWidth = getComputedStyle(this[tab], null).getPropertyValue('width');
        this.setState({
            checkedPos,
            barWidth,
            isIntro:tab == 'intro'
        })

    }

    clickFollow = () => {
        const isFollowed = this.state.isFollowed
        this.setState({
            isFollowed: !isFollowed
        })

        if(!isFollowed){
            Toast.success('关注成功',1)
        }else{
            Toast.fail('已取消关注',1)
        }
    }

    showMore = () => {
        this.setState({
            isxiala:!this.state.isxiala
        })
    }
    likeIt = () => {
        this.setState({
            liked:!this.state.liked
        })
    }

    reqSimilarList = () => {
        this.context.axios.post('/bulubulu/api/video/list',{
            pageNum:3
        })
        .then(({code,msg,data}) => {
            if(code == 1){
                this.setState({
                    similarList:data
                })
            }else{
                console.log(msg)
            }
        })
    }
    toVideoPage = (videoId) => {
        this.props.history.push('/videoPage/' + videoId)
        
    } 
    goBack = ()=>{
        this.props.history.goBack()
    }

    addFavorite = () =>{
        const {token,videoDetail} = this.state
        this.context.axios.post('/bulubulu/api/favorite/t/add',{
            token,
            aid:videoDetail.aid
        })
        .then(({code,msg}) => {
            if(code == -2){
                Toast.fail('请先登录')
            }else if(code == 1){
                Toast.success(msg)
                this.setState({
                    isFavorite:true
                })
            }else if(code == -3){
                this.showAlert()
            }else{
                Toast.fail(msg)
            }
        })
    }
    delFavorite = () => {
        const {token,videoDetail} = this.state
        this.context.axios.post('/bulubulu/api/favorite/t/del',{
            token,
            aid:videoDetail.aid
        })
        .then(({code,msg}) => {
            if(code == 1){
                Toast.success(msg)
                this.setState({
                    isFavorite:false
                })
            }else{
                Toast.fail(msg)
            }
        })
    }

    isFavorite = ()=>{
        const {token,videoDetail} = this.state
        this.context.axios.post('/bulubulu/api/favorite/t/found',{
            token,
            aid:videoDetail.aid
        })
        .then(({code}) => {
            if(code == 1){
                this.setState({
                    isFavorite:true
                })                
            }else{
                this.setState({
                    isFavorite:false
                })  
            }
        })
    }

    showAlert = () => {
        const {delFavorite} = this
        const alertInstance = alert('提示' ,'是否取消收藏', [
          { text: '关闭', onPress: () => console.log('cancel'), style: 'default' },
          { text: '是', onPress: () => delFavorite() },
        ]);
        setTimeout(() => {
          alertInstance.close();
        }, 500000);
    }

    textChange = (ev) => {
        this.setState({
            text:ev.target.value
        })
    }
    sendMsg = () => {
        const {token,text,videoDetail,commentList} = this.state
        const ctime = new Date().getTime()
        this.context.axios.post('/bulubulu/api/comment/t/add',{
            token,
            aid:videoDetail.aid,
            text,
            ctime
        })
        .then(({code,msg,data}) => {
            if(code == 1){
                commentList.push({
                        aid:videoDetail.aid,
                        uname: data.username,
                        message: text,
                        avatar: 'https://image3.ichuanyi.cn/group2/M00/2A/91/CgAANVfYsokEAAAAAAAAACxXdPA600.jpg?imageMogr/v2/auto-orient/thumbnail/130x/quality/60/format/jpg',
                        ctime
                })
                this.setState({
                    commentList
                })
                Toast.success(msg)
            }else if(code == -2){
                Toast.fail('请先登录')
            }else{
                Toast.success(msg)
            }
            
        })
        
    }

    reqCommentList = () => {
        const {videoDetail} = this.state
        this.context.axios.post('/bulubulu/api/comment/list',{
            aid:videoDetail.aid
        })
        .then(({code,msg,list}) => {
            if(code == 1){
                this.setState({
                    commentList:list
                })
            }else{
                console.log(msg)
            }
        })
    }

    playVideo = () =>{
        this.setState({
            isPlay: "none"
        },() => {
            this.player.play()
        })
        
    }

    goTopPlay = () => {
        this.setState({
            isPlay: "none"
        },() => {
            this.player.play()
            window.scrollTo(0,0)
        })
    }
     

    render() {
        const {videoDetail,opacity,checkedPos,barWidth,isFixed,isIntro,isFollowed,isxiala,liked,similarList,isFavorite,commentList,text,isPlay} = this.state
        const {checkedTab,clickFollow,showMore,likeIt,durationFrom,toVideoPage,goBack,addFavorite,textChange,sendMsg,playVideo,goTopPlay} = this
        const {commonUrl} = this.context

        const toFixed1 = num =>{
            if(num >10000){
                num = num /10000
                return num.toFixed(1) + '万'
            }
            return parseInt(num)
        }
        return (
            <div>
                {videoDetail &&
                <div>
                    <div className={classnames(styles.top,{"bgcolor": opacity>1})} ref={(e) => this.topNav = e} >
                        <i className={classnames("iconfont","icon-fanhui",styles.topIcon)} onClick={goBack}></i>
                        {
                            opacity < 0.4 ? null :
                            <i className={classnames("iconfont","icon-bofangqi-bofangxiaodianshi",styles.topIcon)} onClick={goTopPlay}>立即播放</i>
                        }
                        <i className={classnames("iconfont","icon-diandiandianshu",styles.topIcon)}></i>
                    </div>
                    <div className={styles.playerBox} ref={(e) => this.imgWarp = e}>
                        <div className={styles.coverWarp} style={{opacity: opacity,display:isPlay}} onClick={playVideo}></div>
                        <div className={styles.videoImg}>
                            <Player
                            ref={player => {this.player = player; }}
                            playsInline
                            poster={commonUrl + videoDetail.pic}
                            src={videoDetail.source}
                            >
                                <BigPlayButton position="center" />
                            </Player>
                        </div >
                        <i className={classnames('iconfont','icon-bofangqi-bofangxiaodianshi',styles.playerIcon)} style={{display:isPlay}}></i>
                        <div className={styles.duration} style={{display:isPlay}}>{durationFrom} </div>
                    </div>
                                      
                    <div className={styles.tabTitle} style={{position: isFixed ? 'fixed' : 'relative',top:isFixed ? '1rem' : '0'}}  >
                        <div ref={e => this.intro = e} className={classnames(styles.tabItem, {[styles.active] : isIntro})} onClick={ () => checkedTab('intro')} >简介</div>
                        <div ref={e => this.comment = e} className={classnames(styles.tabItem, {[styles.active] : !isIntro})} onClick={ () => checkedTab('comment')}>评论</div>
                        <div className={styles.textBox}>
                            <input className={styles.input} type="text" placeholder="点我发弹幕"/>
                            <span className={styles.btn}>弹</span>
                        </div>
                        <div className={styles.tabBar} 
                            style={{
                                transform:`translate3d(${checkedPos}px,0px,0px)`,
                                width:`${barWidth}`
                        }}></div>
                    </div>

                    {isIntro && 
                    <div className={styles.introInfo}>
                        <div className={styles.upInfo}>
                            <div className={styles.authorInfo}>
                                <img className={styles.upImg} src={require("@/assets/img/swl.jpg")} alt="没有接口" />
                                <div >
                                    <p className={styles.upName}>{videoDetail.author}</p>
                                    <p className={styles.upFans}>{toFixed1(videoDetail.mid / 10)}粉丝</p>
                                </div>
                            </div>
                            <div className={classnames('iconfont',{"icon-tianjia" : !isFollowed},{ "icon-list" : isFollowed},styles.followed)} onClick={clickFollow} style={{backgroundColor: isFollowed ? '#e7e7e7':'rgb(222, 105, 140)',color: isFollowed ? '#666' : '#fff'}}>{isFollowed ? "已关注" : "关注"}</div>
                        </div>
                        <div className={styles.describeInfo}>
                            <div className={classnames(styles.title,isxiala && "ellipsis")}>{videoDetail.title}</div>
                            <i className={classnames('iconfont',{'icon-xialaxiao':isxiala},{'icon-shouqixiao':!isxiala})} onClick={showMore}></i>
                        </div>
                        <div className={styles.playerInfo}>
                            <i className={classnames("iconfont"," icon-bofangshu",styles.item)}>&nbsp;{toFixed1(videoDetail.play)}</i>
                            <i className={classnames("iconfont","icon-danmushu",styles.item)}>&nbsp;{toFixed1(videoDetail.video_review)}</i>
                            <span className={classnames("iconfont",styles.item)}>10-16</span>
                            <span className={classnames("iconfont",styles.item)}>AV{videoDetail.aid}</span>
                        </div>
                        <div className={styles.upReap}>
                            <div className={classnames(styles.likeIt,{[styles.active] : liked })} onClick={likeIt}>
                                <i className={classnames("iconfont","icon-zan",styles.icon)}></i>
                                <p className={styles.text}>{toFixed1(videoDetail.mid /1000)}</p>
                            </div>
                            <div className={classnames(styles.likeIt)}>
                                <i className={classnames("iconfont","icon-cai",styles.icon)}></i>
                                <p className={styles.text}>不喜欢</p>
                            </div>
                            <div className={classnames(styles.likeIt)}>
                                <i className={classnames("iconfont","icon-Bbi",styles.icon)}></i>
                                <p className={styles.text}>{toFixed1(videoDetail.coins)}</p>
                            </div>
                            <div className={classnames(styles.likeIt)} onClick={addFavorite} style={{color:isFavorite? "#fb7299" :"#666"}}>
                                <i className={classnames("iconfont","icon-shoucang",styles.icon)}></i>
                                <p className={styles.text}>{toFixed1(videoDetail.cid /1000)}</p>
                            </div>
                            <div className={classnames(styles.likeIt)}>
                                <i className={classnames("iconfont","icon-fenxiang",styles.icon)}></i>
                                <p className={styles.text}>{toFixed1(videoDetail.pts /1000)}</p>
                            </div>
                        </div>


                        <ul>
                            {
                                similarList.map(e => <li key={e._id} className={styles.similarItem} onClick={() => toVideoPage(e.aid)}>
                                    <img className={styles.similarVideoImg} src={commonUrl + e.pic} alt="请求不到图片" />
                                    
                                    <div className={styles.similarInfo}>
                                        <div className={classnames(styles.title,"ellipsis2")}>{e.title}</div>
                                        <p className={classnames('iconfont','icon-UPzhu',styles.author)}>{e.author}</p>
                                        <div>
                                            <span className={classnames('iconfont','icon-bofangshu',styles.play)}>{toFixed1(e.play)}</span>
                                            <span className={classnames('iconfont','icon-danmushu',styles.video_review)}>{toFixed1(e.video_review)}</span>
                                        </div>
                                    </div>
                                </li>)
                            }
                        </ul>
                    </div>}

                    {!isIntro && <div className={styles.commentInfo}>
                        <ul className={styles.commentBox}>
                        {!commentList.length ? "还没有评论~" : 
                            commentList.map( (e,i) => <li key={i} className={styles.commentItem}>
                                <div className={styles.uAvatar}><img className={styles.img} src={e.avatar} alt="图片显示不出来" /> </div>
                                <div className={styles.msgbox}>
                                    <div className={styles.title}>
                                        <h4 className={styles.uname}>{e.uname}</h4>
                                        <span className={styles.time}>{new Date(e.ctime).toLocaleDateString()}</span>
                                    </div>
                                    
                                    <p className={styles.msg}>{e.message}</p>
                                </div>
                            </li>)

                        }
                        </ul>


                        <div className={styles.bottomIpt}>
                            <input type="text" placeholder="说点什么" className={styles.textIpt} onChange={textChange} value={text} />
                            <span onClick={sendMsg}>发布</span>
                        </div>
                    </div>}

                </div>
                
                }
            </div>
        )
    }

    componentDidMount(){
        const {aid} = this.props.match.params

        this.reqVideoDetail(aid)
        .then(() =>{
            this.isFavorite()
            this.reqCommentList()
        })
        this.reqSimilarList()
        

        const checkedPos = this.intro.getBoundingClientRect().left
        const barWidth = getComputedStyle(this.intro, null).getPropertyValue('width');

        const token = localStorage.getItem('token')
        this.setState({
            checkedPos,
            barWidth,
            token
        })

        window.onscroll = () => {
            let scrollTop = document.body.scrollTop || document.documentElement.scrollTop
            let navHeight = this.imgWarp.clientHeight - this.topNav.clientHeight
            let opacity = scrollTop  / navHeight
            this.setState({
              opacity,
              isFixed: opacity>1
            }) 
        }
    }

    UNSAFE_componentWillReceiveProps(nextProps){
        
        const {aid} = nextProps.match.params

        this.reqVideoDetail(aid)
        .then(() =>{
            this.isFavorite()
            this.setState({
                isPlay: "block"
            },() => {
                this.player.load()
            })
            
            window.scrollTo(0,0)
        })
    }
    componentWillUnmount(){
        window.onscroll = null
    }
}

export default VideoPage
